const fs = require('fs')
const util = require('util')
const crypto = require('crypto')
const readFileAsync = util.promisify(fs.readFile)
const writeFileAsync = util.promisify(fs.writeFile)

const createNonce = () => Math.random().toString(36).substr(2, 15)
const createTimestamp = () => parseInt(new Date().getTime() / 1000, 10) + ''

exports.readFileAsync = async (fpath, encoding) => {
  const data = await readFileAsync(fpath, encoding)

  return data
}
exports.writeFileAsync = async (fpath, content) => {
  const data = await writeFileAsync(fpath, content)

  return data
}

const _sign = (noncestr, ticket, timestamp, url) => {
  const params = [
    'noncestr=' + noncestr,
    'jsapi_ticket=' + ticket,
    'timestamp=' + timestamp,
    'url=' + url
  ]
  const str = params.sort().join('&')
  let shasum = crypto.createHash('sha1')

  shasum.update(str)

  return shasum.digest('hex')
}

exports.sign = (ticket, url) => {
  const noncestr = createNonce()
  const timestamp = createTimestamp()
  const signature = _sign(noncestr, ticket, timestamp, url)

  return {
    noncestr: noncestr,
    timestamp: timestamp,
    signature: signature
  }
}
